package com.idlefish.flutterboost;

import android.app.Activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.flutter.FlutterInjector;
import io.flutter.Log;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineGroup;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class EngineBindings implements MethodChannel.MethodCallHandler {
    private static final String ROUTER_KEY_NAME = "com.bslr.method_channel";

    private MethodChannel methodChannel;
    private FlutterEngine engine;

    /**
     * @param activity
     * @param entryPoint 入口函数名
     * @param parmes     参数
     */
    public EngineBindings(Activity activity, String entryPoint, String parmes) {
        DartExecutor.DartEntrypoint dartEntrypoint = new DartExecutor.DartEntrypoint(FlutterInjector.instance().flutterLoader().findAppBundlePath(), entryPoint);
        FlutterEngineGroup.Options options = new FlutterEngineGroup.Options(activity);
        options.setDartEntrypoint(dartEntrypoint);
        List<String> list = new ArrayList<>();
        if (parmes == null) {
            list.add("");
        }
        list.add(parmes);
        options.setDartEntrypointArgs(list);
        engine = FlutterBoost.instance().getEngineGroup(activity.getApplication()).createAndRunEngine(options);
        methodChannel = new MethodChannel(engine.getDartExecutor().getBinaryMessenger(), ROUTER_KEY_NAME);
        methodChannel.setMethodCallHandler(this);
    }


    public FlutterEngine getEngine() {
        return engine;
    }

    public void detach() {
        if (methodChannel != null) {
            methodChannel.setMethodCallHandler(null);
        }
//        if (engine != null) {
//            engine.destroy();
//        }
    }

    @Override
    public void onMethodCall(@NonNull MethodCall methodCall, @NonNull MethodChannel.Result result) {
        FlutterBoost.instance().dispatchMethodCall(FlutterBoost.instance().getPlugin(), methodCall, result);
    }

    /**
     * 回调Flutter方法
     * @param method 方法名
     * @param parms 参数
     */
    public void invokeMethod(String method, String parms) {
        if (methodChannel != null) {
            methodChannel.invokeMethod(method, parms);
        }
    }
}
